package com.the4man.framework.util.dialect;

/**
 * Created by lenovo on 2017/12/12.
 */
public class OracleDialect extends Dialect {
    public OracleDialect() {
    }

    public String getLimitString(String sql, int offset, int limit) {
        sql = sql.trim();
        boolean isForUpdate = false;
        if(sql.toLowerCase().endsWith(" for update")) {
            sql = sql.substring(0, sql.length() - 11);
            isForUpdate = true;
        }

        StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
        pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
        pagingSelect.append(sql);
        pagingSelect.append(" ) row_ ) where rownum_ > " + offset + " and rownum_ <= " + (offset + limit));
        if(isForUpdate) {
            pagingSelect.append(" for update");
        }

        return pagingSelect.toString();
    }

    public String getOrderByString(String sql, String sortfiled, String orderby) {
        sql = sql.trim();
        boolean isWithUr = false;
        if(sql.toLowerCase().endsWith(" for update")) {
            sql = sql.substring(0, sql.length() - 11);
            isWithUr = true;
        }

        StringBuilder orderSelect = (new StringBuilder(sql.length() + 200)).append("select * from ( ").append(sql).append(" ) ").append(" order by ").append(sortfiled).append(" ").append(orderby);
        if(isWithUr) {
            orderSelect.append(" for update");
        }

        return orderSelect.toString();
    }
}
